package com.yun.partnerSys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.partnerSys.common.BaseResponse;
import com.yun.partnerSys.common.ErrorCode;
import com.yun.partnerSys.common.ResultUtils;
import com.yun.partnerSys.contant.UserConstant;
import com.yun.partnerSys.exception.BusinessException;
import com.yun.partnerSys.model.domain.User;
import com.yun.partnerSys.model.dto.UserTagsDTO;
import com.yun.partnerSys.model.request.UserLoginRequest;
import com.yun.partnerSys.model.request.UserRegisterRequest;
import com.yun.partnerSys.model.vo.FriendVO;
import com.yun.partnerSys.service.UserService;

import com.yun.partnerSys.service.FollowRelationshipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户接口
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private FollowRelationshipService followRelationshipService;


    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> SearchUserByTags(@RequestParam(required = false) List<String> tagNameList
            ,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUserByTags(tagNameList,loginUser);
        return ResultUtils.success(userList);
    }


    // todo 推荐多个，未实现
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommend(long pageSize,long pageNum,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        Page<User> userPage = userService.getRecommend(pageSize,pageNum,loginUser);
        return ResultUtils.success(userPage);
    }


    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user,loginUser);
        return ResultUtils.success(result);
    }

    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num,HttpServletRequest request){
        if(num <= 0 || num > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        return ResultUtils.success(userService.matchUsers(num,loginUser));
    }

    /**
     * 根据id获取用户
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/get/{id}")
    public BaseResponse<User> getUserById(@PathVariable long id) {
        User user = userService.getUserById(id);
        return ResultUtils.success(user);
    }


    /**
     * 关注用户
     *
     * @param id 要关注的用户id
     * @return
     */
    @PostMapping("/dofollow/{id}")
    public BaseResponse<Boolean> followUser(@PathVariable long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Boolean isSuccess = followRelationshipService.followUser(id, loginUser);
        return ResultUtils.success(isSuccess);
    }

    /**
     * 取消关注用户
     *
     * @param id 要取消关注的用户id
     * @return
     */
    @PostMapping("/unfollow/{id}")
    public BaseResponse<Boolean> unFollowUser(@PathVariable long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Boolean isSuccess = followRelationshipService.unFollowUser(id, loginUser);
        return ResultUtils.success(isSuccess);
    }

    /**
     * 判断当前登录用户是否已关注用户
     *
     * @param id      被关注用户id
     * @param request
     * @return
     */
    @GetMapping("/isfans/{id}")
    public BaseResponse<Boolean> isFans(@PathVariable long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        boolean isFans = followRelationshipService.isFans(id, loginUser);
        return ResultUtils.success(isFans);
    }

    @GetMapping("/all")
    public BaseResponse<List<FriendVO>> getAllFriends(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        List<FriendVO> friends = followRelationshipService.getAllFriends(loginUser);
        return ResultUtils.success(friends);
    }


    /**
     * 用户修改标签
     *
     * @param userTagsDTO 新标签数据
     * @param request
     * @return
     */
    @PostMapping("/update/tags")
    public BaseResponse<Boolean> updateTags(@RequestBody UserTagsDTO userTagsDTO, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        String tags = userTagsDTO.getTags();
        Boolean isSuccess = userService.updateTags(tags, loginUser);
        return ResultUtils.success(isSuccess);
    }

    /**
     * 用户头像上传
     *
     * @param file 头像
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String filePath = userService.uploadUserAvatarUrl(file, loginUser);

        return ResultUtils.success(filePath);
    }


}
